<template>
  <div>
    <DynamicTable
      row-key="id"
      show-index
      header-title="水表型号管理"
      :data-request="getManageList"
      :columns="columns"
      bordered
      size="small"
    >
      <template #toolbar>
        <a-button type="primary" @click="openMenuModal({})"> 新增</a-button>
      </template>
    </DynamicTable>
  </div>
</template>

<script lang="ts" setup>
  import { h, ref } from 'vue';
  import ManageForm from './detail/index.vue';

  import { baseColumns, type TableListItem, type TableColumnItem, pageDataObj } from './columns';
  import { getManageList, deleteManage } from '@/api/model/manage';
  import { useTable } from '@/components/core/dynamic-table';
  import { useModal } from '@/hooks/useModal/useModal';
  import { getDictListApi } from '@/api/sys/dict';

  defineOptions({
    name: 'Manage',
  });

  const [DynamicTable, dynamicTableInstance] = useTable();

  const [ModalRender] = useModal();
  const manageref = ref(null);
  // 自定义转码字典
  getDictListApi('MODEL_MANUFACTURER')
    .then((res) => {
      pageDataObj.manufacturerDict = res.map((item) => ({
        label: item.name,
        value: item.code,
      }));
    })
    .then(() => {
      // 改变搜索框数据
      dynamicTableInstance?.getQueryFormRef()?.updateSchema({
        field: `manufacturer`,
        componentProps: {
          options: pageDataObj.manufacturerDict,
        },
      });
    });
  /**
   * @description 打开新增/编辑弹窗
   */
  const openMenuModal = async (record: Partial<TableListItem>) => {
    await ModalRender.show({
      title: `${record.id ? '编辑' : '新增'}水表型号`,
      width: '80vw',
      destroyOnClose: true,
      content: () => {
        return h(ManageForm, { ref: manageref, id: record.id });
      },
      onOk: async () => {
        await manageref.value.saveData();
        dynamicTableInstance?.reload();
      },
    });
    ModalRender.setProps({ fullscreenModel: true });
  };

  const delRowConfirm = async (record: TableListItem) => {
    await deleteManage([record.id]);
    dynamicTableInstance?.reload();
  };

  const columns: TableColumnItem[] = [
    ...baseColumns,
    {
      title: '操作',
      width: 160,
      dataIndex: 'ACTION',
      hideInSearch: true,
      align: 'center',
      fixed: 'right',
      actions: ({ record }) => [
        {
          label: '编辑',
          onClick: () => openMenuModal(record),
        },
        {
          label: '删除',
          popConfirm: {
            title: '你确定要删除吗？',
            onConfirm: () => delRowConfirm(record),
          },
        },
      ],
    },
  ];
</script>
